<template>
<div>
  <h1>角色页面</h1>
  <div class="divTop" v-model="search">
    <span>角色名称</span><el-input v-model="search.roleName" style="width: 220px" placeholder="请输入角色名称"></el-input>
    <span>权限字符</span><el-input v-model="search.roleKey" style="width: 220px" placeholder="请输入权限字符"></el-input>
    <span>状态</span><el-select style="width: 200px" v-model="search.status" placeholder="角色状态">
      <el-option label="正常" value="0"></el-option>
      <el-option label="停用" value="1"></el-option>
    </el-select>
    <span>时间</span>
    <el-date-picker
        style="width: 300px;"
        v-model="search.time"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
    </el-date-picker>
    <p>
      <el-button @click="searchDJ" type="success" size="small" icon="el-icon-search">搜索</el-button>
      <el-button @click="searchCZ" size="small" icon="el-icon-refresh">重置</el-button>
    </p>
  </div>
<!--  中层按钮-->
  <div>
    <el-row class="but-add">
      <el-button type="primary" size="small" @click="doSave('role')">添加</el-button>
      <el-button type="success" size="small" disabled>修改</el-button>
      <el-button type="danger" size="small" @click="deleteRoles" :disabled="isDisabled">批量删除</el-button>
      <el-button type="warning" size="small" @click="derive">导出</el-button>
    </el-row>
  </div>
<!--  数据展示-->
  <el-table
      :data="roles"
      :cell-style="{'text-align':'center'}"
      :header-cell-style="{background:'#E4E7ED','text-align':'center',color:'#000'}"
      @select="selectRoleOneId"
      @select-all="selectRoleAllIds"
      style="width: 100%">
    <el-table-column type="selection"></el-table-column>
    <el-table-column
        prop="roleId"
        label="角色ID"
        width="150">
    </el-table-column>
    <el-table-column
        prop="roleName"
        label="角色名称"
        width="180">
    </el-table-column>
    <el-table-column
        prop="roleKey"
        label="权限字符"
        width="180">
    </el-table-column>
    <el-table-column
        prop="roleSort"
        label="显示顺序"
        width="180">
    </el-table-column>
    <el-table-column
        prop="status"
        label="状态"
        width="180">
<!--      状态开关-->
      <template slot-scope="scop">
        <el-switch v-model="scop.row.status"
                   active-value="0"
                   inactive-value="1"
                   @change="doBut1(scop.row.status,scop.row.roleId)"></el-switch>
      </template>
    </el-table-column>
    <el-table-column
        prop="createTime"
        label="创建时间"
        width="200">
    </el-table-column>
    <el-table-column
        label="操作">
      <template slot-scope="scope">
        <el-button @click="doEdit(scope.row)" type="text" size="small">修改</el-button>
        <el-button @click="openDataWindow(scope.row)" type="text" size="small">数据权限</el-button>
        <el-button @click="deleteRole(scope.row.roleId)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
<!--  分页-->
  <div class="block">
    <el-pagination
        @size-change="sizeTo"
        @current-change="pageTo"
        :current-page="page"
        :page-sizes="[1,5,10,20, 30, 40]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="sizes">
    </el-pagination>
  </div>
<!--  添加或修改弹窗-->
  <el-dialog title="角色信息" width="500px" :visible.sync="role_window">
    <el-form :model="role" :rules="rules" ref="role" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="role.roleName"></el-input>
      </el-form-item>
      <el-form-item label="字符权限" prop="roleKey">
        <el-input v-model="role.roleKey"></el-input>
      </el-form-item>
      <el-form-item label="角色顺序" prop="roleSort">
        <el-input-number v-model="role.roleSort" controls-position="right"></el-input-number>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="role.status">
          <el-radio :label="0" >正常</el-radio>
          <el-radio :label="1" >禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限菜单">
        <el-checkbox v-model="checked1" @change="unfold" label="展开/折叠"></el-checkbox>
        <el-checkbox v-model="checked2" @change="selectAll" label="全选/全不选"></el-checkbox>
        <el-checkbox v-model="checked3" label="父子联动"></el-checkbox>
<!--        树形控件-->
          <el-tree
              style="border: gainsboro solid 1px"
              :data="menus"
              :check-strictly="!checked3"
              show-checkbox
              node-key="menuId"
              ref="tree"
              highlight-current
              :props="defaultProps">
          </el-tree>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="role.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save('role')">确认</el-button>
        <el-button @click="reset('role')">重置</el-button>
        <el-button @click="role_window=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
<!--  数据权限弹窗-->
  <el-dialog title="数据权限" width="500px" :visible.sync="data_window">
    <el-form :model="role" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称">
        <el-input v-model="role.roleName" disabled></el-input>
      </el-form-item>
      <el-form-item label="字符权限">
        <el-input v-model="role.roleKey" disabled></el-input>
      </el-form-item>
      <el-form-item label="数据权限">
        <el-select v-model="role.dataScope" placeholder="请选择">
          <el-option label="全部数据权限" value="1"></el-option>
          <el-option label="自定义数据权限" value="2"></el-option>
          <el-option label="部门数据权限" value="3"></el-option>
          <el-option label="本部门及以下数据权限" value="4"></el-option>
          <el-option label="仅本人数据权限" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="role.dataScope==2" label="权限菜单">
        <el-checkbox v-model="dataChecked1" @change="unfoldDept" label="展开/折叠"></el-checkbox>
        <el-checkbox v-model="dataChecked2" @change="selectAllDept" label="全选/全不选"></el-checkbox>
        <el-checkbox v-model="dataChecked3" label="父子联动"></el-checkbox>
        <!--        树形控件-->
        <el-tree
            style="border: gainsboro solid 1px"
            :data="depts"
            :check-strictly="!dataChecked3"
            show-checkbox
            node-key="deptId"
            ref="treeDept"
            highlight-current
            default-expand-all
            :props="ziDept">
        </el-tree>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editRoleDept">确认</el-button>
        <el-button @click="data_window=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</div>
</template>

<script>
import {saveAs} from "file-saver";
export default{
  name:"RoleView",
  data(){
    return{
      roles:[],
      pages:1,
      page:1,
      size:5,
      sizes:0,
      //弹窗所用的属性
      role:{"roleId":null,"roleName":"","roleKey":"","roleSort":"","dataScope":1,"menuCheckStrictly":1,"deptCheckStrictly":1,"status":"","delFlag":0,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null},
      role_window:false,
      rules:{
        roleName:[{required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleKey:[{required: true, message: '字符权限不能为空', trigger: 'blur' }],
        roleSort:[{required: true, message: '排序不能为空', trigger: 'blur' }],
      },
      menus:[],
      defaultProps: {
        children: 'childMenu',
        label: 'menuName',
      },
      checked1:false,
      checked2:false,
      checked3:true,
      //添加用
      menuIds:[],
      //批量删除的容器
      deleteList:[],
      isDisabled:true,
      //数据权限弹窗
      data_window:false,
      depts:[],
      ziDept: {
        children: 'childDept',
        label: 'deptName',
      },
      dataChecked1:true,
      dataChecked2:false,
      dataChecked3:true,
      deptIds:[],
      //搜索实体
      search:{roleName:null,roleKey:null,status:null,time:[]}

    }
  },
  methods:{
    //分页查询
    selectAllPage(page,size){
      this.page=page;
      this.size=size;
      const staterTime = new Date(this.search.time[0]);
      const endTime = new Date(this.search.time[1]);
      console.log(this.search);
      this.$axios.post("/sysRole/selectAllPage/"+page,{
        size:this.size,
        roleName:this.search.roleName,
        roleKey:this.search.roleKey,
        status:this.search.status,
        staterTime:staterTime,
        endTime:endTime
      })
          .then(result =>{
            if (result.data.code==200){
              this.roles=result.data.data.records;
              this.sizes=result.data.data.total;
              this.pages=result.data.data.pages;
            }
          })
    },
    //页码刷新
    pageTo(val){
      this.selectAllPage(val,this.size);
      this.page=val;
    },
    //条数刷新
    sizeTo(val){
      this.selectAllPage(this.page,val);
      this.size=val;
    },
    //状态开关
    doBut1(status,roleId){
      if (status==0){
        this.$confirm('此操作将启用该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(()=>{
          this.$axios.post("/sysRole/openStatus/"+roleId)
              .then(result =>{
                if (result.data.code==200){
                  this.selectAllPage(this.page,this.size);
                  this.$message({
                    type: 'success',
                    message: result.data.data,
                  });
                }
              })
        }).catch(() => {
          this.selectAllPage(this.page,this.size);
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }else {
        this.$confirm('此操作将停用该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(()=>{
          this.$axios.post("/sysRole/closeStatus/"+roleId)
              .then(result =>{
                if (result.data.code==200){
                  this.selectAllPage(this.page,this.size);
                  this.$message({
                    type: 'success',
                    message: result.data.data,
                  });
                }
              })
        }).catch(() => {
          this.selectAllPage(this.page,this.size);
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }
    },
    //添加打开弹窗前的初始化操作
    doSave(role){
      this.role={"roleId":null,"roleName":"","roleKey":"","roleSort":"","dataScope":1,"menuCheckStrictly":1,"deptCheckStrictly":1,"status":0,"delFlag":0,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null};
      this.selectMenuAll();
      this.checked1=false;
      this.checked2=false;
      this.checked3=true;
      this.role_window=true;
      this.$refs.tree.setCheckedKeys([]);
      this.$refs[role].resetFields();
    },
    //查询菜单数据
    selectMenuAll(){
      this.$axios.get("/sysMenu/selectAllMenuAndChildMenu")
          .then(result =>{
            if (result.data.code==200){
              console.log("菜单："+result.data.data)
              this.menus=result.data.data;
            }
          })
    },
    //展开/折叠事件
    unfold(){
      for(let i=0;i<this.$refs.tree.store._getAllNodes().length;i++){
        this.$refs.tree.store._getAllNodes()[i].expanded=this.checked1;
      }
    },
    //全选/全不选
    selectAll(){
      if (this.checked2){
        this.$refs.tree.setCheckedNodes(this.menus);
      }else {
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    //弹窗重置
    reset(role){
      this.$refs[role].resetFields();
      this.role={"roleId":null,"roleName":"","roleKey":"","roleSort":"","dataScope":1,"menuCheckStrictly":1,"deptCheckStrictly":1,"status":"","delFlag":0,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null};
      this.$refs.tree.setCheckedKeys([]);
      this.checked1=false;
      this.checked2=false;
      this.checked3=true;
    },
    //查询修改的角色所拥有的权限并完成勾选
    showMenuIds(roleId){
      this.$axios.get("/sysRole/selectMenuIdsByRoleId/"+roleId)
          .then(result =>{
            if (result.data.code==200){
              //实现树的选中效果
              console.log("勾选"+result.data.data)
              this.$refs.tree.setCheckedKeys(result.data.data);
            }
          })
    },
    //修改前的初始化操作
    doEdit(role){
      this.role=JSON.parse(JSON.stringify(role));
      console.log(role)
      //判断状态
      if (role.status == '0'){
        this.role.status=0;
      }else {
        this.role.status=1;
      }
      this.checked1=false;
      this.checked2=false;
      this.checked3=true;
      this.showMenuIds(role.roleId)
      this.selectMenuAll();
      this.role_window = true;
    },
    //添加或修改
    save(role){
      if (this.role.roleId==null){//添加
        this.$refs[role].validate((valid) => {
          if (valid) {
            // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
            this.role.createBy=localStorage.getItem("username");
            this.menuIds = this.$refs.tree.getCheckedKeys();
            this.$axios.post("/sysRole/roleAdd",{role:this.role,menuIds:this.menuIds})
                .then(result =>{
                  if (result.data.code==200){
                    this.role_window = false;
                    this.selectAllPage(this.page,this.size);
                    this.$message({
                      message: '恭喜你，'+result.data.data,
                      type: 'success'
                    });
                  }else {
                    this.$message({
                      message: '警告哦，'+result.data.message,
                      type: 'warning'
                    });
                  }
                })
          } else {
            console.log("没写完")
            return false;
          }
        });

      }else {//修改
        // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
        this.role.updateBy=localStorage.getItem("username");//测试给默认值后续删
        this.menuIds = this.$refs.tree.getCheckedKeys();
        this.$axios.put("/sysRole/roleEdit",{role:this.role,menuIds:this.menuIds})
            .then(result =>{
              if (result.data.code==200){
                this.role_window = false;
                location.reload();    //强制刷新
                this.$message({
                  message: '恭喜你，'+result.data.data,
                  type: 'success'
                });
              }else {
                this.$message({
                  message: '警告哦，'+result.data.message,
                  type: 'warning'
                });
              }
            })
      }
    },
    //删除
    deleteRole(roleId){
      this.$confirm('是否删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(()=>{
        this.$axios.delete("/sysRole/deleteRole/"+roleId)
            .then(result =>{
              if (result.data.code==200){
                if (this.roles.length==1 && this.page>1){
                  console.log(this.roles.length)
                  this.selectAllPage(this.page-1,this.size);
                }else {
                  this.selectAllPage(this.page,this.size);
                }
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
              }
            })
      }).catch(() => {
        this.selectAllPage(this.page,this.size);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取多行数据
    selectRoleOneId(val){
      this.deleteList=[];
      for (let i = 0; i < val.length; i++) {
        this.deleteList[i]=val[i].roleId;
      }
      console.log(this.deleteList)
      this.deletesBut();
    },
    //获取全部行数据
    selectRoleAllIds(val){
      this.deleteList=[];
      for (let i = 0; i < val.length; i++) {
        this.deleteList[i]=val[i].roleId;
      }
      console.log(this.deleteList)
      this.deletesBut();
    },
    //判断批量删除按钮
    deletesBut(){
      if (this.deleteList.length>1){
        this.isDisabled = false;
      }else {
        this.isDisabled = true;
      }
    },
    //批量删除点击事件
    deleteRoles(){
      this.$confirm('此操作将删除多个角色，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(()=>{
        this.$axios.delete("/sysRole/deleteRoles/"+this.deleteList)
            .then(result =>{
              if (result.data.code==200){
                if (this.roles.length==1 && this.page>1){
                  this.selectAllPage(this.page-1,this.size);
                }else if (this.deleteList.length == this.roles.length) {
                  this.selectAllPage(this.page-1,this.size);
                }else {
                  this.selectAllPage(this.page,this.size);
                }
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
                this.deleteList=[];
                this.isDisabled=true;
              }
            })
      }).catch(() => {
        this.selectAllPage(this.page,this.size);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //查询部门树
    selectDepts(){
      this.$axios.get("/sysDept/deptTree")
          .then(result =>{
            if (result.data.code==200){
              this.depts=result.data.data;
            }
          })
    },
    //通过角色id查询部门id,并完成部门树勾选
    showDeptIds(roleId){
      this.$axios.get("/sysDept/selectDeptIdsByRoleId/"+roleId)
          .then(result =>{
            if (result.data.code==200){
              console.log(result.data.data)
              //实现树的选中效果
              this.$refs.treeDept.setCheckedKeys(result.data.data);
            }
          })
    },
    //打开数据权限弹窗
    openDataWindow(role){
      this.dataChecked1=true;
      this.dataChecked2=false;
      this.dataChecked3=true;
      this.role={"roleId":null,"roleName":"","roleKey":"","roleSort":"","dataScope":"","menuCheckStrictly":1,"deptCheckStrictly":1,"status":"","delFlag":0,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null};
      this.role = JSON.parse(JSON.stringify(role));
      this.selectDepts();
      this.showDeptIds(this.role.roleId);
      this.data_window = true;
    },
    //展开/折叠事件
    unfoldDept(){
      for(let i=0;i<this.$refs.treeDept.store._getAllNodes().length;i++){
        this.$refs.treeDept.store._getAllNodes()[i].expanded=this.dataChecked1;
      }
    },
    //全选/全不选
    selectAllDept(){
      if (this.dataChecked2){
        this.$refs.treeDept.setCheckedNodes(this.depts);
      }else {
        this.$refs.treeDept.setCheckedKeys([]);
      }
    },
    //数据权限确定按钮
    editRoleDept(){
      this.deptIds = this.$refs.treeDept.getCheckedKeys();
      this.$axios.put("/sysRole/editRoleDept",{role:this.role,deptIds:this.deptIds})
          .then(result =>{
            if (result.data.code==200){
              this.data_window = false;
              this.selectAllPage(this.page,this.size);
              this.$message({
                message: '恭喜你，'+result.data.data,
                type: 'success'
              });
            }else {
              this.$message({
                message: '警告哦，'+result.data.message,
                type: 'warning'
              });
            }
          })
    },
    //搜索重置点击
    searchCZ(){
      this.search={roleName:null,roleKey:null,status:null,time:[]};
      this.selectAllPage(this.page,this.size);
    },
    //搜索点击
    searchDJ(){
      this.selectAllPage(1,this.size);
    },
    //导出
    derive(){
      this.$prompt('请输入导出文件名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        let roleIds = this.deleteList;
        console.log(roleIds);
        this.$axios.get("/sysRole/derive?roleIds="+roleIds,{responseType: 'arraybuffer'})
            .then(result =>{
              const blob = new Blob([result.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
              saveAs(blob, value + '.xlsx');
              this.selectAllPage(this.page,this.size);
              this.$message({
                type: 'success',
                message: '文件：'+value+'导出成功！'
              });
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导出！'
        });
      });
    }


  },
  mounted() {
    this.selectAllPage(this.page,this.size);
  }
}
</script>

<style scoped>
.block{
  float: right;
  margin-right: 30px;
  margin-top: 30px;
}
.but-add{
  float: left;
  margin-bottom: 20px;
}
.divTop{
  margin-bottom: 20px;
  text-align: left;
}
.divTop>span{
  margin-right: 10px;
  margin-left: 20px;
}
</style>
